package main

import (
	"golang-websocket-service/routers"
	"golang-websocket-service/tools"
	"log"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	// 创建 websocket 服务
	tools.WsSrv = tools.NewWebsocketServer()
	r := gin.Default()

	// 客户端方式发消息
	r.POST("/client", func(ctx *gin.Context) {
		uid := ctx.DefaultPostForm("uid", "999")
		params := map[string]interface{}{
			"uid":      uid,
			"username": "admin",
		}
		// 注意/broadcasting就是下面对应的r.GET("/broadcasting", func(ctx *gin.Context) {})http路由
		wc, err := tools.NewWebsocketClient("ws://127.0.0.1:8000/broadcasting", params)
		if err != nil {
			ctx.JSON(200, gin.H{
				"code":    400,
				"message": err.Error(),
				"data":    []interface{}{},
			})

			return
		}

		err = wc.SendMessage(map[string]interface{}{
			"event_type":  "broadcasting",
			"type":        1,
			"conent":      "xxxxxxx",
			"image_url":   "",
			"is_read":     0,
			"status":      1,
			"create_time": time.Now().Format("2006-01-02 15:04:05"),
		})
		if err != nil {
			ctx.JSON(200, gin.H{
				"code":    400,
				"message": err.Error(),
				"data":    []interface{}{},
			})

			return
		}

		ctx.JSON(200, gin.H{
			"code":    200,
			"message": "发送消息成功",
			"data":    []interface{}{},
		})

	})

	// // 广播
	// r.GET("/broadcasting", func(ctx *gin.Context) {
	// 	log.Println(" ----------------- 广播 ----------------- ")
	// 	fromUid := ctx.DefaultQuery("from_uid", "0")
	// 	log.Println("fromUid =", fromUid)

	// 	// 设置事件
	// 	ctx.Request.Header.Set("event_type", "broadcasting")

	// 	// HandleRequest将http请求升级为websocket连接，并将其分派给melody实例处理
	// 	ws.WebsocketSrv.HandleRequest(ctx.Writer, ctx.Request)
	// })

	// 推送订单过期消息
	r.GET("/orderExpired", func(ctx *gin.Context) {
		oid := ctx.DefaultQuery("oid", "0")
		log.Println("oid =", oid)

		// 客户端通过header传递参数
		log.Println("params = ", ctx.GetHeader("params"))

		// 设置事件
		ctx.Request.Header.Set("event_type", "orderExpired")

		// HandleRequest将http请求升级为websocket连接，并将其分派给melody实例处理
		err := tools.WsSrv.WebsocketSrv.HandleRequest(ctx.Writer, ctx.Request)
		if err != nil {
			log.Println("err = ", err.Error())
		}
		log.Println("------------ orderExpired ------------")
	})

	// 加载路由配置
	routers.ApiRouters(r)

	// 运行服务
	r.Run(tools.ServerHost + ":" + tools.ServerPort)
}
